package skin;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

import static org.example.SkinAnalysisExample.splitJson;

public class SkinAnalysisOptimizedcopy {
    private static final String API_KEY = "3UznLENkCCGHI1VBxtqlfzxy2Rg6zv6J";
    private static final String SECRET_KEY = "g3iL_gem_67PeKi96nVUGNinjDYeZGqn";
    // 高级版
    private static final String API_URL = "https://api-cn.faceplusplus.com/facepp/v1/skinanalyze_advanced";

    public static void main(String[] args) {
        // 图片路径
        File imageFile = new File("C:\\Users\\Administrator\\Pictures\\mz\\6.jpg");
        try {
            String result = analyzeSkin(imageFile);
            splitJson(result);
            String parsedResult = printOptimizedResult(result);
            // 指定输出流的编码为 UTF-8
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8));
            writer.println(parsedResult);
            writer.flush();
        } catch (IOException e) {
            // 指定异常信息输出的编码为 UTF-8
            PrintWriter errorWriter = new PrintWriter(new OutputStreamWriter(System.err, StandardCharsets.UTF_8));
            e.printStackTrace(errorWriter);
            errorWriter.flush();
        } catch (IllegalArgumentException e) {
            // 指定异常信息输出的编码为 UTF-8
            PrintWriter errorWriter = new PrintWriter(new OutputStreamWriter(System.err, StandardCharsets.UTF_8));
            errorWriter.println(e.getMessage());
            errorWriter.flush();
        }
    }

    //    json结果集分段
    public static void splitJson(String jsonString) {
        JSONObject jsonObject = new JSONObject(jsonString);
        for (String key : jsonObject.keySet()) {
            Object value = jsonObject.get(key);
            System.out.println(key + ": " + value);
        }
    }

    public static String analyzeSkin(File imageFile) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(API_URL);

        // 添加请求参数
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("api_key", API_KEY, ContentType.create("text/plain", StandardCharsets.UTF_8));
        builder.addTextBody("api_secret", SECRET_KEY, ContentType.create("text/plain", StandardCharsets.UTF_8));
        builder.addBinaryBody("image_file", imageFile, ContentType.APPLICATION_OCTET_STREAM, imageFile.getName());

        HttpEntity multipart = builder.build();
        httpPost.setEntity(multipart);

        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();

        // 获取响应结果并指定编码为 UTF-8
        String responseString = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);

        // 解析 JSON 并检查是否有错误信息
        JSONObject jsonObject = new JSONObject(responseString);
        if (jsonObject.has("error_message")) {
            throw new IllegalArgumentException("照片不合格: " + jsonObject.getString("error_message"));
        }
        if (jsonObject.isEmpty()) {
            throw new IllegalArgumentException("照片不合格: 无法解析 JSON");
        }
        // 解析 JSON 并获取 "result" 部分
        JSONObject resultObject = jsonObject.optJSONObject("result");

        return resultObject != null ? resultObject.toString() : "{}"; // 如果 result 为空，返回空 JSON
    }

    public static String printOptimizedResult(String jsonString) {
        JSONObject jsonObject = new JSONObject(jsonString);

        if (jsonObject.isEmpty()) {
            throw new IllegalArgumentException("照片不合格: 无法解析 JSON");
        }

        StringBuilder chineseResult = new StringBuilder();
        chineseResult.append("皮肤分析结果如下：\n");

        chineseResult.append("-----------干油性分析----------").append("\n");
        // 皮肤类型
        JSONObject skinType = jsonObject.getJSONObject("skin_type");
        int skintype = skinType.getInt("skin_type");
        String typeDescription;
        switch (skintype) {
            case 0:
                typeDescription = "油性皮肤";
                break;
            case 1:
                typeDescription = "干性皮肤";
                break;
            case 2:
                typeDescription = "中性皮肤";
                break;
            case 3:
                typeDescription = "混合性皮肤";
                break;
            default:
                typeDescription = "未知";
        }
        chineseResult.append("皮肤类型: ").append(typeDescription).append("\n");
        //毛孔
        FacialPores(jsonObject, "pores_jaw", "下巴毛孔是否粗大", chineseResult);
        FacialPores(jsonObject, "pores_right_cheek", "左脸颊毛孔是否粗大", chineseResult);
        FacialPores(jsonObject, "pores_left_cheek", "右脸颊毛孔是否粗大", chineseResult);
        FacialPores(jsonObject, "pores_forehead", "额头毛孔是否粗大", chineseResult);
        //    黑头
        JSONObject blackhead = jsonObject.getJSONObject("blackhead");
        int bh = blackhead.getInt("value");
        String bhDescription;
        switch (bh) {
            case 0:
                bhDescription = "无黑头";
                break;
            case 1:
                bhDescription = "轻度";
                break;
            case 2:
                bhDescription = "中度";
                break;
            case 3:
                bhDescription = "重度";
                break;
            default:
                bhDescription = "未知";
        }
        chineseResult.append("黑头: ").append(bhDescription).append("\n");

        chineseResult.append("-----------干油性分析----------").append("\n");
        // 肤色
        JSONObject skinColorValue = jsonObject.getJSONObject("skin_color");
        int color = skinColorValue.getInt("value");
        String skinDescription;
        switch (color) {
            case 0:
                skinDescription = "透白";
                break;
            case 1:
                skinDescription = "白皙";
                break;
            case 2:
                skinDescription = "自然";
                break;
            case 3:
                skinDescription = "小麦";
                break;
            case 4:
                skinDescription = "黝黑";
                break;
            default:
                skinDescription = "未知";
        }
        chineseResult.append("肤色: ").append(skinDescription).append("\n");
        //        ITA
        JSONObject ITA = jsonObject.getJSONObject("skintone_ita");
        int ita = ITA.getInt("ITA");
        String itaDescription;
        if (ita > 56 && ita < 90) {
            itaDescription = "Very light";
        } else if (ita > 43 && ita <= 56) {
            itaDescription = "Light";
        } else if (ita > 36 && ita <= 43) {
            itaDescription = "intermediate";
        } else if (ita > 20 && ita <= 36) {
            itaDescription = "tan";
        } else if (ita > 10 && ita <= 20) {
            itaDescription = "brown";
        } else if (ita > -90 && ita <= 10) {
            itaDescription = "Dark";
        } else {
            itaDescription = "异常值";
        }
        chineseResult.append("ITA: ").append(itaDescription).append("\n");
        //        HA
        JSONObject HA = jsonObject.getJSONObject("skin_hue_ha");
        int ha = HA.getInt("HA");
        String haDescription;
        if (ha > 49 && ha <= 90) {
            haDescription = "偏黄";
        } else if (ha >= 46 && ha <= 49) {
            haDescription = "中性";
        } else if (ha >= 10 && ha < 46) {
            haDescription = "偏红";
        } else {
            haDescription = "异常值";
        }
        chineseResult.append("HA: ").append(haDescription).append("\n");
        //        色斑
        JSONObject SkinSpot = jsonObject.getJSONObject("skin_spot");
        JSONArray SkinSpotArray = SkinSpot.optJSONArray("rectangle");
        int SkinSpotCount = SkinSpotArray != null ? SkinSpotArray.length() : 0;
        chineseResult.append("色斑个数: ").append(SkinSpotCount).append("\n");
        //        痣
        JSONObject Mole = jsonObject.getJSONObject("mole");
        JSONArray MoleArray = Mole.optJSONArray("rectangle");
        int MoleCount = MoleArray != null ? MoleArray.length() : 0;
        chineseResult.append("痣个数: ").append(MoleCount).append("\n");

        chineseResult.append("-----------衰老分析----------").append("\n");
        // 皮肤年龄
        JSONObject skinAge = jsonObject.getJSONObject("skin_age");
        int age = skinAge.getInt("value");
        chineseResult.append("皮肤年龄: ").append(age).append("\n");
        processSingleWrinkle(jsonObject, "forehead_wrinkle", "抬头纹", chineseResult);
        processSingleWrinkle(jsonObject, "crows_feet", "鱼尾纹", chineseResult);
        processSingleWrinkle(jsonObject, "eye_finelines", "眼部细纹", chineseResult);
        processSingleWrinkle(jsonObject, "glabella_wrinkle", "眉间纹", chineseResult);
        processSingleWrinkle(jsonObject, "nasolabial_fold", "法令纹", chineseResult);

        chineseResult.append("-----------痤疮分析----------").append("\n");
        //        痘痘
        JSONObject Acne = jsonObject.getJSONObject("acne");
        JSONArray AcneArray = Acne.optJSONArray("rectangle");
        int AcneCount = AcneArray != null ? AcneArray.length() : 0;
        chineseResult.append("痘痘个数: ").append(AcneCount).append("\n");
        //        闭口粉刺
        JSONObject ClosedComedones = jsonObject.getJSONObject("closed_comedones");
        JSONArray ClosedComedonesArray = ClosedComedones.optJSONArray("rectangle");
        int ClosedComedonesCount = ClosedComedonesArray != null ? ClosedComedonesArray.length() : 0;
        chineseResult.append("闭口粉刺个数: ").append(ClosedComedonesCount).append("\n");

        chineseResult.append("-----------眼部分析----------").append("\n");
        //        黑眼圈
        JSONObject DarkCircle = jsonObject.getJSONObject("dark_circle");
        int darkcircle = DarkCircle.getInt("value");
        String darkcircleDescription;
        switch (darkcircle) {
            case 0:
                darkcircleDescription = "无黑眼圈";
                break;
            case 1:
                darkcircleDescription = "色素型黑眼圈";
                break;
            case 2:
                darkcircleDescription = "血管型黑眼圈";
                break;
            case 3:
                darkcircleDescription = "阴影型黑眼圈";
                break;
            default:
                darkcircleDescription = "未知";
        }
        chineseResult.append("黑眼圈: ").append(darkcircleDescription).append("\n");
        //        眼袋
        JSONObject eyePouch = jsonObject.getJSONObject("eye_pouch");
        int eyepouch = eyePouch.getInt("value");
        if (eyepouch == 0) {
            chineseResult.append("眼袋: 无").append("\n");
        } else {
            chineseResult.append("眼袋: 有").append("\n");
            //            眼袋程度
            JSONObject eyePouchSeverity = jsonObject.getJSONObject("eye_pouch_severity");
            int eyePouchSeverityValue = eyePouchSeverity.getInt("value");
            String eyePouchSeverityDescription;
            switch (eyePouchSeverityValue) {
                case 0:
                    eyePouchSeverityDescription = "轻度";
                    break;
                case 1:
                    eyePouchSeverityDescription = "中度";
                    break;
                case 2:
                    eyePouchSeverityDescription = "重度";
                    break;
                default:
                    eyePouchSeverityDescription = "未知";
            }
            chineseResult.append("眼袋程度: ").append(eyePouchSeverityDescription).append("\n");
        }
        return chineseResult.toString();
    }

    //面部皱纹
    private static void processSingleWrinkle(JSONObject jsonObject, String key, String label, StringBuilder result) {
        JSONObject wrinkleObject = jsonObject.optJSONObject(key);
        if (wrinkleObject != null) {
            int value = wrinkleObject.optInt("value", -1);
            String description;
            switch (value) {
                case 0:
                    description = "无";
                    break;
                case 1:
                    description = "有";
                    break;
                default:
                    description = "未知";
            }
            result.append(label).append(": ").append(description).append("\n");
        }
    }

    //面部毛孔
    private static void FacialPores(JSONObject jsonObject, String key, String label, StringBuilder result) {
        JSONObject wrinkleObject = jsonObject.optJSONObject(key);
        if (wrinkleObject != null) {
            int value = wrinkleObject.optInt("value", -1);
            String description;
            switch (value) {
                case 0:
                    description = "否";
                    break;
                case 1:
                    description = "是";
                    break;
                default:
                    description = "未知";
            }
            result.append(label).append(": ").append(description).append("\n");
        }
    }
}